package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit) {
        //key、value、time、时间单位
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        //设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        //写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存穿透
     *
     * @param id
     * @return
     */
    public <R, ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback,
            Long time, TimeUnit unit) {
        //1.从redis中查询缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        //2.判断redis中是否存在
        if (StrUtil.isNotBlank(json)) {
            //3.存在，返回信息
            return JSONUtil.toBean(json, type);
        }

        //-缓存穿透：判断是否命中的是空值
        if (json != null) {
            //返回错误信息
            return null;
        }

        //4.不存在，根据id查询数据库
        R r = dbFallback.apply(id);

        //4.1 数据库中不存在，返回404
        if (r == null) {
            //-缓存穿透：缓存空对象
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            //返回错误信息
            return null;
        }

        //4.2存在，先把数据写入redis中，再去返回
        this.set(key, r, time, unit);

        //5.返回信息
        return r;
    }

    /**
     * 缓存击穿：
     * 使用逻辑过期处理
     *
     * @param id
     * @return
     */
    public <R, ID> R queryWithLogicalExpire(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback,
            Long time, TimeUnit unit, String lockKeyPrefix, Long lockTime, TimeUnit lockUnit) {
        //1.从redis中查询缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        //2.判断redis中是否存在
        if (StrUtil.isBlank(json)) {
            //3.未命中，直接返回null（因为数据已经预热过了，如果你查不到，说明你不是热点key，返回null）
            return null;
        }

        //4.命中，说明是热点key，把Json->Java对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //4.1 判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //4.2 未过期，返回信息
            return r;
        }
        //4.3 已过期，需要缓存重建

        //5.缓存重建
        //5.1 获取互斥锁
        String lockKey = lockKeyPrefix + id;
        boolean isLock = tryLock(lockKey, lockTime, lockUnit);

        //5.2 判断是否获取到锁
        if (isLock) {
            //再次检测是否过期
            if (expireTime.isAfter(LocalDateTime.now())) {
                //未过期，返回信息
                return r;
            }
            //5.2.1 成功，开启新的线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //查询数据库
                    R r1 = dbFallback.apply(id);
                    //重建缓存
                    this.setWithLogicalExpire(key, r1, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }

        //5.2.2 失败，返回商铺信息（过期的）
        return r;
    }

    /**
     * 线程池
     */
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 获取锁
     *
     * @param key
     * @return
     */
    private boolean tryLock(String key, Long lockTTL, TimeUnit lockUnit) {
        Boolean flag = stringRedisTemplate.opsForValue()
                                          .setIfAbsent(key, "1", lockTTL, lockUnit);

        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     *
     * @param key
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
